package com.itheima.netty.c7;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

// @Slf4j
public class TestByteBuf {
    public static void main(String[] args) {
        //创建 ByteBuf会自动扩容
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        log(buffer);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 300; i++) {
            sb.append(1);
        }
        buffer.writeBytes(sb.toString().getBytes());
        // log(buffer);
        // System.out.println(buffer.readByte());
        // log(buffer);
        buffer.markReaderIndex();//读之前做个标记
        buffer.resetReaderIndex();//重置到标记位置 reset
        buffer.getByte(1);//get开头方法不会改变read index

        //实现不同
        // ByteBuf buffer = ByteBufAllocator.DEFAULT.heapBuffer();
        // ByteBuf buffer = ByteBufAllocator.DEFAULT.directBuffer();
        // System.out.println(buffer.getClass());

        //池化 4.1之后默认池化（除了安卓）
        //-Dio.netty.allocator.type={unpooled|pooled}


        //handler中**谁是最后使用者，谁负责 release**

        ByteBuf origin = ByteBufAllocator.DEFAULT.buffer(10);
        origin.writeBytes(new byte[]{1, 2, 3, 4, 5, 6});
        // origin.readByte();
        //slice切片 对于底层没有拷贝，是同一块内存，切完后不能写入，切完后最好分别释放
        ByteBuf slice0 = origin.slice(0, 3);
        ByteBuf slice1 = origin.slice(0, 2);
        // System.out.println(ByteBufUtil.prettyHexDump(slice0));
        // System.out.println(ByteBufUtil.prettyHexDump(slice1));
        // System.out.println(ByteBufUtil.prettyHexDump(origin));
        // slice.writeByte(5); 如果执行，会报 IndexOutOfBoundsException 异常

        CompositeByteBuf bufs = ByteBufAllocator.DEFAULT.compositeBuffer();
        ByteBuf origin0 = ByteBufAllocator.DEFAULT.buffer();
        origin0.writeBytes(new byte[]{1, 2, 3, 4, 5, 6});
        ByteBuf origin1 = ByteBufAllocator.DEFAULT.buffer();
        origin1.writeBytes(new byte[]{7, 8, 9, 10, 11, 12});
        bufs.addComponents(true, origin0, origin1);
        log(origin0);
        log(origin1);
        log(bufs);
    }

    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }
}
